package com.rbac.modules.system.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rbac.modules.system.entity.SysRole;
import com.rbac.modules.system.mapper.SysRoleMapper;
import com.rbac.modules.system.service.SysRoleService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService {
    @Override
    public List<String> getRoleCodesByUserId(Long userId) {
        return baseMapper.selectRoleCodesByUserId(userId);
    }

    @Override
    public boolean existsByCode(String roleCode) {
        return lambdaQuery()
                .eq(SysRole::getRoleCode, roleCode)
                .exists();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRoleToUser(Long userId, String roleCode) {
        // 先删除用户原有的角色关联
        baseMapper.deleteUserRoleByUserId(userId);
        
        // 获取角色ID
        SysRole role = lambdaQuery()
                .eq(SysRole::getRoleCode, roleCode)
                .one();
        
        if (role != null) {
            // 添加新的角色关联
            baseMapper.insertUserRole(userId, role.getId());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignPermissionToRole(Long roleId, Long permissionId) {
        // 检查是否已经存在该权限关联
        if (!baseMapper.existsRolePermission(roleId, permissionId)) {
            // 添加新的权限关联
            baseMapper.insertRolePermission(roleId, permissionId);
        }
    }
} 